from django import template
from django.conf import settings
from django.template import Template, Context, RequestContext
from django.template.defaultfilters import escapejs
from django.contrib.sites.models import Site

register = template.Library()

def render_from_string(template_string, context):
    t = Template(template_string)
    c = Context(context)
    return t.render(c)

UNIVERSAL_CODE = """
<div id="disqus_thread"></div>
<script type="text/javascript">
    {% if debug %}var disqus_developer = 1;{% endif %}
    var disqus_shortname = '{{shortname}}';
    {% if url %}var disqus_url = '{{url}}';{% endif %}
    {% if disqus_title %}var disqus_title = '{{disqus_title}}'{% endif %}
    (function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
</script>
"""

COMMENTCOUNT_CODE = """
<script type="text/javascript">
    var disqus_shortname = '{{shortname}}';
    var disqus_apikey = 'fIiuoGHcgIKNSE0OJZ1VTDikxBmhLKtao2V5uzubErHJH6RFOA04Qyvq6lvmWPQm';

    $.each($('a[href*="#disqus_thread"]'), function(index, data) {
        var anchor = $(this);
        $.ajax({
          url: 'http://disqus.com/api/3.0/threads/details.jsonp',
          dataType: 'jsonp',
          data: {
            api_key : disqus_apikey,
            thread  : 'link:http://{{site_domain}}' + anchor.attr('href').split("#")[0],
            forum  : disqus_shortname
          },
          success: function(data) {
            if (data.response.posts > 0) {
                anchor.text(data.response.posts);
                anchor.fadeIn();
            }
          }
        });
    });
    
</script>
"""

@register.simple_tag(takes_context = True)
def disqus_embed(context, title=None, identifier=None, url=None):
    if title and identifier:
        url = 'http://%s%s' % (Site.objects.get_current().domain, escapejs(url))
        ctx = {
            'title':title,
            'identifier': identifier,
            'url':url,
            'shortname': settings.DISQUS_SHORTNAME
        }
        return render_from_string(UNIVERSAL_CODE, RequestContext(context['request'], ctx))
    else:
        return ""

@register.simple_tag(takes_context = True)
def disqus_count(context):
    current_site =  Site.objects.get_current()
    return render_from_string(COMMENTCOUNT_CODE, RequestContext(context['request'], {
        'site_domain': current_site.domain,
        'shortname': settings.DISQUS_SHORTNAME,
    }))
